package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RegexUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;
import static com.hmdp.utils.SystemConstants.USER_NICK_NAME_PREFIX;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result sendCode(String phone, HttpSession session) {
        //1、先判断是否是合法的phone number
        if (!RegexUtils.isPhoneInvalid(phone)){
            return Result.fail("错误的电话号码！");
        }

        //2、生成验证码
        String  code = RandomUtil.randomNumbers(6);
/*
        //保存验证码到session里
        session.setAttribute("code",code);*/

        //保存验证码到redis里
        ValueOperations valueOperations = stringRedisTemplate.opsForValue();
        valueOperations.set(LOGIN_CODE_KEY+phone,code,LOGIN_CODE_TTL, TimeUnit.MINUTES);

        //调用短信接口，发送接口，省略
        log.info("调用短信接口，发送短信：{}",code);

        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm, HttpSession session) {

        //1、先判断是否是合法的phone number
        if (!RegexUtils.isPhoneInvalid(loginForm.getPhone())){
            return Result.fail("错误的电话号码！");
        }

        //校验code是否一致
        //Object code = session.getAttribute("code");
        String code = stringRedisTemplate.opsForValue().get(LOGIN_CODE_KEY + loginForm.getPhone());
        if (code == null||!code.equals(loginForm.getCode())){
            return Result.fail("验证码错误");
        }
        //查询数据库的user表(mybatis-plus的查询)
        User user = query().eq("phone", loginForm.getPhone()).one();

        //如果用户不存在，则创建用户
        if (user==null){
            log.info("插入用户！");
            user=createUser(loginForm.getPhone());
        }
/*
        //将用户user放到session里
        session.setAttribute("user",user);*/
        //-----把user放到redis里
        //随机生成token
        String token = UUID.randomUUID().toString(true);
        //把dto转成map集合
        UserDTO userDTO=new UserDTO();
        BeanUtils.copyProperties(user,userDTO);
        //Map<String, Object> userMap = BeanUtil.beanToMap(userDTO);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create()
                        .setIgnoreNullValue(true)
                        .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString()));
        //放入redis的hash类型中去，对应token:userMap格式
        stringRedisTemplate.opsForHash().putAll(LOGIN_USER_KEY+token,userMap);
        //设置有效期
        stringRedisTemplate.expire(LOGIN_USER_KEY+token,LOGIN_USER_TTL, TimeUnit.MINUTES);

        return Result.ok(token);
    }

    private User createUser(String phone) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword("123456");
        user.setNickName(USER_NICK_NAME_PREFIX+RandomUtil.randomString(10));
        //保存到表里
        save(user);
        return user;
    }
}
